package com.dhms.uikit

import android.content.Context
import android.icu.text.SimpleDateFormat
import android.net.Uri
import android.os.Build
import android.util.Log
import android.util.TypedValue
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
import androidx.annotation.RequiresApi
import java.text.ParsePosition
import java.util.*

@RequiresApi(Build.VERSION_CODES.N)
fun Date.toFormatDate(format: String = "yyyy-MM-dd HH:mm:ss"): String {
    return SimpleDateFormat(format, Locale.CHINA).format(this)
}

@ColorInt
fun Context.getColorFromAttr(
    @AttrRes attrColor: Int,
    typedValue: TypedValue = TypedValue(),
    resolveRefs: Boolean = true
): Int {
    theme.resolveAttribute(attrColor, typedValue, resolveRefs)

    return typedValue.data
}


fun parseStringFromInt(
    num: Int
): String = num.toString()


/**
 * Pass your date format and no of days for minus from current
 * If you want to get previous date then pass days with minus sign
 * else you can pass as it is for next date
 * @param dateFormat
 * @param days
 * @return Calculated Date
 */
fun getCalculatedDate(baseDate: Date, dateFormat: String?, field: Int, days: Int): String {
    val cal = Calendar.getInstance()
    cal.time = baseDate
    val s = SimpleDateFormat(dateFormat, Locale.US)
    cal.add(field, days)
    return s.format(Date(cal.timeInMillis))
}

//"2006-01-02 15:04:05"
fun String.toDate(format: String = "yyyy-MM-dd HH:mm:ss"): Date? {
    return try {
        SimpleDateFormat(format, Locale.CHINA).parse(this, ParsePosition(0))
    } catch (e: Exception) {
        Log.e("Time", "$this, $e")
        null
    }
}

fun isLeapYear(year: Int): Boolean = if (year % 100 != 0 && year % 4 == 0) {
    true
} else year % 100 == 0 && year % 400 == 0

fun isLocalResource(uri: Uri): Boolean {
    return uri.toString().startsWith("file://")
}

